<template>
  <div class="login-account">
    <el-form :rules="rules" :model="account" ref="accountRef">
      <el-form-item label="账号" prop="name">
        <el-input v-model="account.name"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="account.password" show-password></el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref } from 'vue'
import { useStore } from 'vuex'
import { rules } from '../config/account-rule'
import localCache from '@/utils/cache'
import type { FormInstance } from 'element-plus'

export default defineComponent({
  setup() {
    const store = useStore()

    const account = reactive({
      name: localCache.getCache('name') ?? '',
      password: localCache.getCache('password') ?? ''
    })

    const accountRef = ref<FormInstance>()

    const accountLogin = (isKeepPasswrod: boolean) => {
      accountRef.value?.validate((valid) => {
        if (valid) {
          // 记住密码
          if (isKeepPasswrod) {
            localCache.setCache('name', account.name)
            localCache.setCache('password', account.password)
          } else {
            localCache.removeCache('name')
            localCache.removeCache('password')
          }
          store.dispatch('login/accountLoginActions', account)
        }
      })
    }

    return {
      account,
      rules,
      accountLogin,
      accountRef
    }
  }
})
</script>

<style scoped></style>
